﻿# -*- coding:UTF-8 -*-
#!/usr/bin/env python

import error404 , error500

from shorturl import model
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class RedirectShortURL(webapp.RequestHandler):
    def get(self):
        try:
            if not (self.request.headers['Host'] in ('yourhostname' , 'localhost:8084')) :
                return error404.error404(self)
            else:
                self.__queryUrl()
        except Exception , exceptions:
            error500.error500(self , ' %s %s' % (type(exceptions) , exceptions))
    
    def __queryUrl(self):
        originalUrlObjs = db.GqlQuery("SELECT * FROM ShortUrl WHERE shortUrl = '%s'" % self.request.path.replace('/' , ''))
        try:
            originalUrlObj = originalUrlObjs[0]
        except IndexError:
            return error404.error404(self , path = 'shorturl/404.html')
        else:
            self.redirect(originalUrlObj.originalUrl , 301)
            originalUrlObj.clicks += 1
            originalUrlObj.put()
            

application = webapp.WSGIApplication(
                                     [('/[^/]*' , RedirectShortURL)] ,
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()